import constant from './constant'
import {
	toast
} from './dailog'
import {
	goPage
} from './utils';

const COS = require('cos-js-sdk-v5');

export function http(url, data = {}, method = 'POST') {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '请稍等...',
		});
		uni.request({
			url: ~url.indexOf('http') ? url : constant.URL + url,
			method,
			data: {
				token: uni.getStorageSync('token'),
				...data
			},
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
			},
			success: (res) => {
				uni.hideLoading();
				// console.info('HTTP请求', url, data, res)
				if (res.statusCode !== 200) {
					// 请求报错
					toast('服务器正忙，请稍后再试');
				} else if (res.data.code == 402) {
					// 需要登录
					goPage('/pages/mine/login')
				} else if (res.data.code != 0) {
					// 操作失败
					toast(res.data.msg);
				} else {
					if (res.data.data.token) {
						uni.setStorageSync('token', res.data.data.token)
					}
					// 操作成功
					resolve(res.data);
				}
			},
		});
	});
}

export async function getCredentials() {
	let credentials = uni.getStorageSync('credentials')
	if (!credentials || credentials.expiredTime * 1000 < Date.now()) {
		// 过期重新获取凭证
		const res = await http('/config/sts');
		credentials = res.data
		uni.setStorageSync('credentials', credentials)
	}

	const signature = COS.getAuthorization({
		SecretId: credentials.credentials.tmpSecretId,
		SecretKey: credentials.credentials.tmpSecretKey,
		Method: 'POST',
		Pathname: '/'
	});

	return {
		host: credentials.host,
		formData: {
			success_action_status: 200,
			Signature: signature,
			'x-cos-security-token': credentials.credentials.sessionToken,
			'Content-Type': ''
		}
	}
}
